package threadPool;


import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @author: 李德才
 * @description:
 * @create: 2020-12-20 16:48
 **/

/**
 * 窃取线程池 ===> 当自己线程中的任务执行完毕，则分担其他线程池中没有执行完的任务
 */
public class T12_WorkStealingPool {

    public static void main(String[] args) {

        /**
         * =============>  Executors.newWorkStealingPool();
         * -----------------------------------------------------------
         * 每个线程都有单独的队列
         * 当自己队列中的任务执行完毕，则分担其他线程池中没有执行完的任务
         *     public static ExecutorService newWorkStealingPool() {
         *         return new ForkJoinPool
         *             (Runtime.getRuntime().availableProcessors(),
         *              ForkJoinPool.defaultForkJoinWorkerThreadFactory,
         *              null, true);
         *     }
         */
        ExecutorService executorService = Executors.newWorkStealingPool();
        System.out.println(Runtime.getRuntime().availableProcessors());

        executorService.execute(new MyRunnable(1000));
        executorService.execute(new MyRunnable(2000));
        executorService.execute(new MyRunnable(2000));
        executorService.execute(new MyRunnable(2000));
        executorService.execute(new MyRunnable(2000));

        //由于产生的是精灵线程（守护线程、后台线程），主线程不阻塞的话，看不到输出
        try {
            System.in.read();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    static class MyRunnable implements Runnable {
        int time;

        MyRunnable(int t) {
            this.time = t;
        }

        @Override
        public void run() {
            try {
                TimeUnit.MILLISECONDS.sleep(time);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.err.println(time + " =========> " + Thread.currentThread().getName());
        }
    }

}
